﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Mall.Data;

namespace Solution
{
    /// <summary>
    /// 权限验证属性类
    /// </summary>
    public class RequireAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 用户权限列表
        /// </summary>
        public UserAuthModel[] UserAuthList
        {
            get
            {
                return AuthorizedUser.Current.UserAuthList;
            }
        }

        /// <summary>
        /// 登录用户票据
        /// </summary>
        public string UserLoginTicket
        {
            get
            {
                return AuthorizedUser.Current.UserLoginTicket;
            }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            ////验证是否是登录用户
            var identity = filterContext.HttpContext.User.Identity;
            if (identity.IsAuthenticated)
            {


                var actionName = filterContext.ActionDescriptor.ActionName;
                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

                if (string.IsNullOrEmpty(UserLoginTicket))
                {
                    //用户的Session, Cookie都过期，需要重新登录
                    filterContext.Result = new RedirectResult("/passport/login?returnUrl=" + HttpContext.Current.Request.RawUrl);
                    //filterContext.HttpContext.Response.Redirect("~/passport/login", false);
                }
                else
                {

                    //判断是否是匿名访问
                    var attr = filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>();
                    bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);

                    //如果匿名访问，就直接跳过了
                    if (isAnonymous) return;

                    if (!"1".Equals(SessionHelper.GetSession("SESSION_SUPER_PERMISSION")))  //并不是超管所有权限
                    {

                        //验证用户操作是否在权限列表中，不在权限列表中，跳转未授权页面
                        if (!HasActionQulification(actionName, controllerName))
                        {
                            throw new Exception("未授权访问...");
                            //虽然是登录用户，但没有该Action的权限，跳转到“未授权访问”页面
                            //filterContext.HttpContext.Response.Redirect("~/Home/UnAuthorized", true);
                            StandardResult rs = new StandardResult()
                            {
                                State = 1,
                                Message = "未授权访问"
                            };
                            filterContext.Result = new JsonResult()
                            {
                                Data = rs,
                                JsonRequestBehavior = JsonRequestBehavior.AllowGet
                            };
                            //throw new Exception("");
                        }
                    }
                }
            }
            else
            {
                filterContext.Result = new RedirectResult("/passport/login?returnUrl=" + HttpContext.Current.Request.RawUrl);

                //未登录用户，则判断是否是匿名访问
                //var attr = filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AllowAnonymousAttribute>();
                //bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);

                //if (!isAnonymous)
                //    //未验证（登录）的用户, 而且是非匿名访问，则转向登录页面
                //    filterContext.HttpContext.Response.Redirect("~/passport/login", true);
            }
        }

        /// <summary>
        /// 从权限列表验证用户是否有权访问Action
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        private bool HasActionQulification(string actionName, string controllerName)
        {
            //取出缓存中的所有菜单功能节点
            List<Sys_MenuAction> maList = CacheHelper.GetCache("GLOBAL_MENU_ACTION") as List<Sys_MenuAction>;
            string userId = FormTicketHelper.GetUserId();
            //var roles = userRole.Split(',');

            var menuItem = maList.FirstOrDefault(o => o.A_State == 0 && controllerName.Equals(o.A_Controller, StringComparison.CurrentCultureIgnoreCase) && actionName.Equals(o.A_Action, StringComparison.CurrentCultureIgnoreCase));
            if (menuItem == null)
            {
                return false;
            }
            //取出缓存中的角色拥有的权限，并判断当前用户角色是否拥有此权限
            List<Sys_MenuAction> rmList = SessionHelper.GetSession("GLOBAL_ROLE_MENU"+ userId) as List<Sys_MenuAction>;
            return rmList!=null &&  rmList.Any(o => o.A_Id == menuItem.A_Id);


            //此处可以校验用户的其它权限条件
            //var notAllowed = HasOtherLimition(userName);
            //var result = (auth != null) && notAllowed;
            //return result;

            return false;
        }
    }
}
